package com.appspile.android.ANMP.applocksexy.application.controller;

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.graphics.drawable.Drawable;

import com.appspile.android.ANMP.applocksexy.application.object.ApplockPackageInfo;
import com.appspile.android.ANMP.applocksexy.commons.LogUtils;
import com.appspile.android.ANMP.applocksexy.global.GlobalApp;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by TRUNG on 2/4/2015.
 */
public class CollectAppInstalled {

    private static CollectAppInstalled mInstance;
    final static String TAG = "COLLECT APP INSTALLED";

    public static synchronized CollectAppInstalled getInstance()
    {
        if(mInstance == null)
        {
            mInstance = new CollectAppInstalled();
        }
        return mInstance;
    }
    class PInfo {

    }

    public ArrayList<ApplockPackageInfo> getPackages() {
        ArrayList<ApplockPackageInfo> apps = getInstalledApps(false); /* false = no system packages */
        final int max = apps.size();
        for (int i=0; i<max; i++) {
            LogUtils.d(TAG,"=======================");
            logInfo(apps.get(i));
            LogUtils.d(TAG,"=======================");
        }
        return apps;
    }

    private ArrayList<ApplockPackageInfo> getInstalledApps(boolean getSysPackages) {
        ArrayList<ApplockPackageInfo> res = new ArrayList<ApplockPackageInfo>();
        List<PackageInfo> packs = GlobalApp.getInstance().getPackageManager().getInstalledPackages(0);
        for(int i=0;i<packs.size();i++) {
            PackageInfo p = packs.get(i);
//            if ((!getSysPackages) && (p.versionName == null)) {
//                continue ;
//            }
            ApplockPackageInfo packgeInfo = new ApplockPackageInfo();
            packgeInfo.setAppName(p.applicationInfo.loadLabel(GlobalApp.getInstance().getPackageManager()).toString());
            packgeInfo.setIcon(p.applicationInfo.loadIcon(GlobalApp.getInstance().getPackageManager()));
            packgeInfo.setPakgeName(p.packageName);
            packgeInfo.setVersionName(p.versionName);
            packgeInfo.setVersionCode(p.versionCode);
            packgeInfo.setSystem(isSystemPackage(p));
            res.add(packgeInfo);
        }
        return res;
    }


    private boolean isSystemPackage(PackageInfo packageInfo) {
        return ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
    }

    private void logInfo(ApplockPackageInfo packageInfo) {
        LogUtils.d(TAG, packageInfo.getPakgeName()
                + "\t" + packageInfo.getAppName()
                + "\t" + packageInfo.getVersionName()
                + "\t" + packageInfo.getVersionCode()
                + "\t" + packageInfo.isSystem());
    }
}
